package com.alm.handle.util;


import com.alm.common.exception.base.BaseException;
import com.alm.util.Misc;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageUtil {

    /**
     * 从服务器获取一张图片的宽度、高度.
     */
    public static int[] getServerImageWidthHeight(String imageAddress) {
        int[] arr = new int[2];
        try {
            FileInputStream fis = new FileInputStream(new File(imageAddress));
            return getImageWidthHeight(fis);
        } catch (Exception e) {
            e.printStackTrace();
            return arr;
        }
    }

    /**
     * 获取上传图片的宽度、高度.
     */
    public static int[] getImageWidthHeight(MultipartFile multiFile) {
        int[] arr = new int[2];
        try {
            if (multiFile == null || multiFile.isEmpty())
                return arr;
            return getImageWidthHeight(multiFile.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return arr;
        }
    }

    /**
     * 返回图片宽度、高度.
     */
    public static int[] getImageWidthHeight(InputStream is) {
        int[] arr = new int[2];
        if (is == null)
            return arr;
        try {
            BufferedImage bi = ImageIO.read(is);
            arr[0] = bi.getWidth();//图片宽度 250px
            arr[1] = bi.getHeight();//图片高度 128px
            return arr;
        } catch (Exception e) {
            e.printStackTrace();
            return arr;
        }
    }

    public static Boolean isCheckWH(String path, Integer width, Integer height) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                throw new RuntimeException("找不到图片信息");
            }
            BufferedImage bi = ImageIO.read(file);
            int minx = bi.getMinX();
            int miny = bi.getMinY();
            int fileWidth = bi.getWidth() - minx;//图片宽度 250px
            int foleheight = bi.getHeight() - miny;//图片高度 128px
            if ((fileWidth != width) || (foleheight != height)) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取图片像素.
     */
    public static String getImagePixel(String imagePath,
                                       Integer imageLayer,
                                       Boolean isYellor) {
        try {
            File file = new File(imagePath);
            if (!file.exists()) {
                return null;
            }
            BufferedImage bi = ImageIO.read(file);
            int minx = bi.getMinX();
            int miny = bi.getMinY();
            int width = bi.getWidth();//图片宽度 250px
            int height = bi.getHeight();//图片高度 128px
            //
            int byteNum = (bi.getHeight() / 8) * bi.getWidth();
            System.out.println("FILE size:" + file.length() + ", byteNum:" + byteNum + ", width:" + width + ", height:" + height + ", minx:" + minx + ", miny:" + miny);
            //
            byte[][] redArr = new byte[height][width];
            byte[][] whiteArr = new byte[height][width];
            byte[][] yellor = new byte[height][width];
            byte[][] green = new byte[height][width];
            for (int i = miny; i < height; i++) {
                for (int j = minx; j < width; j++) {
                    int[] rgb = new int[3];
                    //将一个像素数字转换为RGB数字
                    int pixel = bi.getRGB(j, i);
                    rgb[0] = (pixel & 0xff0000) >> 16;
                    rgb[1] = (pixel & 0xff00) >> 8;
                    rgb[2] = (pixel & 0xff);
                    //黑白优化-黑
//                    if (rgb[0] < 160 && rgb[1] < 160 && rgb[2] < 160) {
//                        redArr[i][j] = 0;//图片的白色像素，设置红色图层着色
//                        whiteArr[i][j] = 0;
//                        continue;
//                    }
                    int type = compareColor(new Color(rgb[0], rgb[1], rgb[2]));
                    switch (type) {
                        case 0:
                            redArr[i][j] = 1;
                            whiteArr[i][j] = 0;
                            green[i][j] = 1;
                            yellor[i][j] = 1;
                            break;
                        case 1:
                            redArr[i][j] = 0;
                            whiteArr[i][j] = 1;
                            green[i][j] = 1;
                            yellor[i][j] = 1;
                            break;
                        case 2:
                            redArr[i][j] = 0;
                            whiteArr[i][j] = 0;
                            green[i][j] = 1;
                            yellor[i][j] = 1;
                            break;
                        case 3:
                            redArr[i][j] = 1;
                            whiteArr[i][j] = 1;
                            green[i][j] = 1;
                            yellor[i][j] = 1;
                            break;
                        case 4:
                            redArr[i][j] = 1;
                            whiteArr[i][j] = 1;
                            green[i][j] = 1;
                            yellor[i][j] = 1;
                            break;
                    }
                }
            }

            StringBuilder reddata = processArray(redArr, width);
            StringBuilder whiteData = processArray(whiteArr, width);
            StringBuilder yellorData = processArray(yellor, width);
            StringBuilder greenData = processArray(green, width);

            String colorLayer = reddata.toString();
            String whiteLayer = whiteData.toString();
            String there;
            String resultData = colorLayer + whiteLayer;
            if (imageLayer == 4) {
                if (isYellor) {
                    there = yellorData.toString();
                } else {
                    there = greenData.toString();
                }
                resultData = resultData + there;
            }
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static StringBuilder processArray(byte[][] array, Integer width) {
        StringBuilder sb20 = new StringBuilder();
        StringBuilder sb22 = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                sb20.append(array[i][(width - 1) - j]);//从上向下读取 width-1=127
                if (sb20.length() == 8) {
                    int bin = Integer.parseInt(sb20.toString(), 2);
                    String hex = Misc.int2hexStr2(bin);
                    sb22.append(hex);
                    sb20.setLength(0);
                }
            }
            if (sb20.length() != 0) {
                int bin = Integer.parseInt(sb20.toString(), 2);
                String hex = Misc.int2hexStr2(bin);
                sb22.append(hex);
            }
        }
        return sb22;
    }

    /**
     * 根据每包限制拆分图片数据
     *
     * @param resultData    目标字符串
     * @param lth           每包限制
     * @param imageDataList 拆分后的图片数据列表
     * @return java.util.List<java.lang.String>
     * @author: 詹泽峰
     * @date: 2024/8/8 10:37
     */
    public static List<String> getData(String resultData, Integer lth, List<String> imageDataList) {
        int sumData = resultData.length() % lth == 0 ? resultData.length() / lth : resultData.length() / lth + 1;
        for (int i = 0; i < sumData; i++) {
            if (resultData.length() == 0) {
                break;
            }
            if (resultData.length() < lth) {
                imageDataList.add(resultData);
                break;
            }
            imageDataList.add(resultData.substring(0, lth));
            resultData = resultData.substring(lth);
        }
        return imageDataList;
    }

    public static double getColorSemblance(Color color1, Color color2) {
        long rmean = ((long) color1.getRed() + (long) color2.getRed()) / 2;
        long r = (long) color1.getRed() - (long) color2.getRed();
        long g = (long) color1.getGreen() - (long) color2.getGreen();
        long b = (long) color1.getBlue() - (long) color2.getBlue();
        return Math.sqrt((((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8));
    }

    public static int compareColor(Color color1) {
        double[] number = new double[5];
        number[0] = getColorSemblance(color1, Color.RED);
        number[1] = getColorSemblance(color1, Color.white);
        number[2] = getColorSemblance(color1, Color.black);
        number[3] = getColorSemblance(color1, Color.green);
        number[4] = getColorSemblance(color1, Color.yellow);
        return getType(number);
    }

    //所得负数  所以获取最大值
    public static int getType(double[] arr) {
        double min = arr[0];
        int type = 0;
        for (int i = 1; i < arr.length; i++) {
            if (min > arr[i]) {
                min = arr[i];
                type = i;
            }
        }
        return type;
    }
}